// const baseImgUrl = 'http://localhost:8080/dist/images/';
const baseImgUrl = "https://test-wap.maidyx.net/maidyx_wap/images/";
let apiUrl = "http://gop500.anxl.com.cn/";
let axUrl = "http://gop500.anxl.com.cn:8086/router?";
let loginUrl = "http://gop500.anxl.com.cn:8087/mainPage.json?Login_SessionId=";

var b = function () {
    var url = location.href;
    var testPro = /http:\/\/open.anxl.com.cn/g; //发布

    var resPro = testPro.test(url);
    if (resPro) {
        apiUrl = 'http://open.anxl.com.cn/';
        axUrl = 'http://open.anxl.com.cn:8086/router?';
        loginUrl = "http://open.anxl.com.cn:8087/mainPage.json?Login_SessionId="
    }
    // if(testPre.test(url)) {
    //     apiUrl = 'http://open.anxl.com.cn/';
    //     axUrl = 'http://open.anxl.com.cn:8086/router?';
    //     loginUrl = "http://open.anxl.com.cn:8087/mainPage.json?Login_SessionId="
    // }
}()

function scroll(fn, trg = null) {
    var $trg = '';
    if (trg) {
        $trg = trg;
    } else {
        $trg = $('.infinite-content');
    }
    var beforeScrollTop = $trg.scrollTop(),
        fn = fn || function () { };

    $trg.scroll(function () {
        var afterScrollTop = $(this).scrollTop(),
            delta = afterScrollTop - beforeScrollTop;
        if (delta === 0) return false;

        var t = $(this).scrollTop();
        var height = $(this).find('div').eq(0).height();
        var screenHeight = $(this).height();

        fn((delta > 0 ? "down" : "up"), (height - (screenHeight + t)));
        beforeScrollTop = afterScrollTop;
    }, false);
}



var initSendCode = function ($trg) {
    var count = 60;
    var isSend = false;
    var timer = null;
    return function ({
        cb = null,
        end = false
    }) {
        //终止
        if (end) {
            $trg.text('重新发送60s');
            clearInterval(timer);
            isSend = false;
            count = 60;
            return
        }
        //判断是否在发送状态
        if (!isSend) {
            $trg.text(60);
            isSend = true;
            if (cb) cb();
            timer = setInterval(function () {
                if (count > 0) {
                    $trg.text(--count);
                } else {
                    clearInterval(timer);
                    count = 60;
                    isSend = false;
                    $trg.text('重新发送60s');
                }
            }, 1000)
        }
    }
};

var getArg = function (arg) {
    var url = location.href;
    var args = url.split("?")[1];
    if (args) {
        var argsArray = args.split("&");
    }
    var result = {};
    for (let p in argsArray) {
        var a = argsArray[p].split("=");
        var b = a[1];
        if (a.length >= 3) {
            for (var j = 2; j < a.length; j++) {
                b = b + '=' + a[j];
            }
            result[a[0]] = b;
        } else {
            result[a[0]] = a[1];
        }
    }
    return result[arg];
}

function setLocalData(key, val, type = 'ses') {
    if (!key) {
        return
    }

    if (localStorage || sessionStorage) {
        if (type == 'loc') localStorage[key] = val;
        if (type == 'ses') sessionStorage[key] = val;
    } else {
        window.key = val;
    }
    return val;
}

function getLocalData(key, type = 'ses') {
    if (!key) {
        return false
    }
    if (localStorage || sessionStorage) {
        if (type == 'loc') return localStorage[key];
        if (type == 'ses') return sessionStorage[key];
    } else {
        return window.key;
    }
}


function $doAjax(arg) {
    return new Promise((resolve, reject) => {
        var obj = arg;
        obj.success = function (res) {
            resolve(res);
        }
        $.ajax(obj);
    })
}


function getUerAgent() {
    var ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        //在微信中打开
        return 'wechat'
    }
    if (ua.match(/AlipayClient/i) == 'alipayclient') {
        return "alipay";
    }
    return 'wechat'
}


function getDevice() {
    var agent = navigator.userAgent;
    var test1 = /iPhone/;
    var test2 = /Android/;
    if (test1.test(agent)) {
        return 1
    }

    if (test2.test(agent)) {
        return 2
    }

    return 3
}

function getType(arg) {
    var gettype = Object.prototype.toString;
    var type = gettype.call(arg);
    return type.slice(8, type.length - 1);
}

function JumpMap(arg, name) {
    var agent = navigator.userAgent;
    var test = /iPhone/;
    if (test.test(agent)) {
        location.href = `baidumap://map/geocoder?location=${arg[0]},${arg[1]}&coord_type=gcj02&src=`
    } else {
        location.href = `bdapp://map/marker?location=${arg[0]},${arg[1]}&title=${name}&traffic=on`
    }
}


function initApi(cb, apiList = [], url = '') {
    if (getUerAgent() == 'wechat') {
        getWechatPara(cb, apiList, url);
    }
    if (getUerAgent() == "alipay") {
        getAlipayPara(cb);
    }
}


function getWechatPara(cb, apiList, url) {
    $.ajax({
        type: 'post',
        data: {
            url: url
        },
        url: apiUrl + 'helper/wechat_jssdk_sign',
        success: function (res) {
            if (res.status == 1) {
                loadScript('http://res.wx.qq.com/open/js/jweixin-1.0.0.js', function () {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.data.appid, // 必填，企业号的唯一标识，此处填写企业号corpid
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature, // 必填，签名，见附录1
                        jsApiList: apiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });

                    wx.ready(function () {
                        setTimeout(() => {
                            cb && cb();
                        }, 250)
                    });
                })
            }
        }
    })
}

function getAlipayPara(cb) {
    loadScript('https://a.alipayobjects.com/g/h5-lib/alipayjsapi/3.0.6/alipayjsapi.min.js', function () {
        // 由于机制问题，JSAPI注入是异步过程，时序无法保证。
        // 如果使用原生AlipayJSBridge接口，需要先监听AlipayJSBridgeReady事件后再调用原生JSAPI接口。
        cb && cb();
    })
}


function loadScript(url, cb) {
    var hd = document.getElementsByTagName('head')[0],
        js = document.createElement('script');
    js.src = url;
    js.type = "text/JavaScript";
    if (js.addEventListener) {
        js.addEventListener("load", function () {
            cb && cb()
        }, false);
    } else if (js.attachEvent) {
        js.attachEvent("onreadystatechange", function () {
            if (js.readyState === "loaded" || js.readyState === "complete") {
                cb && cb()
            }
        });
    }
    hd.appendChild(js);
}

function imgPreLoader(img = []) {
    img.forEach(val => {
        var imgEle = new Image();
        imgEle.src = val;
    })
}

Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}


function checkInput(trg) {
    let result = false;
    switch (trg.id) {
        case 'loginName':
        case 'userName':
            result = checkNormalType(trg);
            break;

        case 'code':
            result = checkCode(trg);
            break;

        case 'phone':
            result = checkPhone(trg);
            break;

        case 'email':
            result = checkEmail(trg);
            break;

        case 'password':
            result = passwordCheck(trg);
            break;

        case 'cpassword':
            result = passwordConfirm(trg);
            break;

        case 'default':
            break;
    }

    //处理普通
    function checkNormalType(trg) {
        let value = String.trim((trg.value));

        if (value.length <= 0) {
            addErroTips(trg, '账号不能为空');
            return false;
        }
        if (value.length >= 50) {
            addErroTips(trg, '账号长度不能超过50位');
            return false;
        }
        removeErroTips(trg);
        return true
    }

    //校验code
    function checkCode(trg) {
        let value = String.trim((trg.value));
        if (value.length <= 0) {
            addErroTips(trg, '输入验证码');
            return false;
        } else {
            removeErroTips(trg);
            return true;
        }
    }

    //处理手机号校验
    function checkPhone(trg) {
        let value = trg.value;
        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (value.length <= 0) {
            addErroTips(trg, '手机号不能为空');
            return false;
        } else {
            if (!myreg.test(value)) {
                addErroTips(trg, '手机号格式不正确');
                return false;
            } else {
                removeErroTips(trg);
                return true;
            }
        }

    }

    //处理邮箱校验
    function checkEmail(trg) {
        var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
        let value = trg.value;
        if (value.length <= 0) {
            addErroTips(trg, '邮箱不能为空');
            return false;
        } else {
            if (!reg.test(value)) {
                addErroTips(trg, '邮箱格式不正确');
                return false;
            } else {
                removeErroTips(trg);
                return true;
            }
        }
    }
    //处理密码校验
    function passwordCheck(trg) {
        let value = trg.value;
        if (value.length <= 0) {
            addErroTips(trg, '密码不能为空');
            return false;
        } else {
            var reg = /^[\w]{6,12}$/
            if (!reg.test(value)) {
                addErroTips(trg, '密码规则：6-12位字母或数字');
                return false;
            } else {
                removeErroTips(trg);
                return true;
            }
        }
    }
    //处理密码两次校验
    function passwordConfirm(trg) {
        let value = trg.value;
        if (value.length <= 0) {
            addErroTips(trg, '密码不能为空');
            return false;
        } else {
            let oldPassword = $('#password').val();
            if (oldPassword !== value) {
                addErroTips(trg, '两次输入的密码不一致');
                return false;
            } else {
                removeErroTips(trg);
                return true;
            }
        }
    }
    //添加校验错误信息
    function addErroTips(trg, errInfo = 'err') {
        let $err = $('#err_' + trg.id);
        if ($err.length > 0) {
            $err.html(`${errInfo}!!`)
        } else {
            let $parent = $(trg).parents('.form_c_input');

            $(trg).after(`<p class="err-tips" id="err_${trg.id}">${errInfo}!!</p>`)
        }
    }

    //移除教研错误信息
    function removeErroTips(trg) {
        let $err = $('#err_' + trg.id);
        $err.remove();
    }


    return result
}


function timeModify(time) {
    let ob = time.replace(/\-/g, '/');

    return ob.slice(2)
}

function setLoginInfo(data) {
    sessionStorage.setItem('loginInfo', JSON.stringify(data));
}


export {
    setLoginInfo,
    timeModify,
    imgPreLoader,
    initApi,
    JumpMap,
    getType,
    getDevice,
    scroll,
    baseImgUrl,
    initSendCode,
    apiUrl,
    axUrl,
    getArg,
    setLocalData,
    getLocalData,
    $doAjax,
    getUerAgent,
    checkInput,
    loginUrl,
    loadScript,
    getDay
}

//IE 浏览器兼容检测

function IEVersion() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7) {
            return 7;
        } else if (fIEVersion == 8) {
            return 8;
        } else if (fIEVersion == 9) {
            return 9;
        } else if (fIEVersion == 10) {
            return 10;
        } else {
            return 6;//IE版本<=7
        }
    } else if (isEdge) {
        return 'edge';//edge
    } else if (isIE11) {
        return 11; //IE11  
    } else {
        return -1;//不是ie浏览器
    }
}
function getDay(timeStr) {
    var a = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    timeStr = timeStr.replace(/-/g, '/');
    var week = new Date(timeStr).getDay();  
    return a[week]
}

+function () {
    if (IEVersion() != -1 && IEVersion() <= 8) {
        $('body').hide();
        alert('请选择IE9以上的版本浏览！');
    }
}()

